<template>
  <div class="content-area">
    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="16">
        <el-col :span="4">
          <div class="stat-card">
            <div class="stat-icon total">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.totalCount }}</div>
              <div class="stat-label">总排班数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="stat-card">
            <div class="stat-icon active">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.activeCount }}</div>
              <div class="stat-label">启用排班</div>
            </div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="stat-card">
            <div class="stat-icon doctor">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.doctorCount }}</div>
              <div class="stat-label">医生排班</div>
            </div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="stat-card">
            <div class="stat-icon nurse">
              <el-icon><Female /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.nurseCount }}</div>
              <div class="stat-label">护士排班</div>
            </div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="stat-card">
            <div class="stat-icon pharmacist">
              <el-icon><MessageBox /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.pharmacistCount }}</div>
              <div class="stat-label">药剂师排班</div>
            </div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="stat-card">
            <div class="stat-icon staff">
              <el-icon><UserFilled /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.staffCount }}</div>
              <div class="stat-label">其他人员</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选卡片 -->
    <div class="filter-card">
      <div class="filter-row">
        <div class="filter-item">
          <div class="filter-label">科室/部门</div>
          <el-select
            v-model="filters.department_id"
            placeholder="请选择科室/部门"
            clearable
            filterable
            :filter-method="filterDepartmentOptions"
            @change="handleDepartmentChange"
          >
            <el-option
              v-for="dept in filteredDepartmentOptions"
              :key="dept.value"
              :label="dept.label"
              :value="dept.value"
            />
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">人员类型</div>
          <el-select
            v-model="filters.staff_type"
            placeholder="请选择类型"
            clearable
          >
            <el-option
              v-for="type in staffTypeOptions"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">人员</div>
          <el-select
            v-model="filters.staff_id"
            placeholder="请选择人员"
            clearable
            filterable
            :filter-method="filterStaffOptions"
          >
            <el-option
              v-for="staff in filteredStaffOptions"
              :key="staff.value"
              :label="staff.label"
              :value="staff.value"
            />
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">排班类型</div>
          <el-select
            v-model="filters.schedule_type"
            placeholder="请选择类型"
            clearable
          >
            <el-option
              v-for="type in ScheduleTypeOptions"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">状态</div>
          <el-select
            v-model="filters.is_active"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="启用" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </div>
      </div>
      <div class="action-buttons">
        <el-button @click="resetFilters">重置</el-button>
        <el-button type="primary" @click="searchSchedules">查询</el-button>
        <el-button type="success" @click="showAddScheduleDialog">
          <el-icon><Plus /></el-icon>
          新增排班模板
        </el-button>
        <el-button type="warning" @click="generateWeeklySchedule">
          <el-icon><MagicStick /></el-icon>
          生成周排班
        </el-button>
        <el-button type="info" @click="showBatchOperationDialog">
          <el-icon><Operation /></el-icon>
          批量操作
        </el-button>
      </div>
    </div>

    <!-- 排班表格 -->
    <div class="schedule-table">
      <div class="table-header">
        <div class="table-title">排班模板列表</div>
        <div class="table-tools">
          <el-button type="primary" @click="exportSchedule">
            <el-icon><Document /></el-icon>
            导出排班表
          </el-button>
          <el-button @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
      <!--表格数据-->
      <el-table
        :data="schedules"
        style="width: 100%"
        v-loading="loading"
        stripe
        ref="scheduleTable"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="人员信息" min-width="200">
          <template #default="{ row }">
            <div class="staff-info">
              <div class="staff-avatar">
                <el-avatar :size="40" :src="row.avatar">
                  <span class="avatar-text">{{
                    getStaffTypeIcon(row.staff_type)
                  }}</span>
                </el-avatar>
              </div>
              <div>
                <div class="staff-name">{{ row.staff_name }}</div>
                <div class="staff-details">
                  {{ formatStaffType(row.staff_type) }} ·
                  {{ row.department_name }}
                  <el-tag
                    v-if="row.professional_title"
                    size="small"
                    effect="plain"
                  >
                    {{ row.professional_title }}
                  </el-tag>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="星期安排" width="140">
          <template #default="{ row }">
            <div class="week-days">
              <el-tag
                v-for="day in row.week_days"
                :key="day"
                size="small"   
                class="week-day-tag"             
                :class="getWeekDayClass(day)"
                
              >
                {{ formatWeekDay(day) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="班次时间" width="120">
          <template #default="{ row }">
            <div class="time-slot-info">
              <el-tag :type="getShiftType(row.time_slot)" size="small">
                {{ formatTimeSlot(row.time_slot) }}
              </el-tag>
              <div class="time-range">{{ formatTimeRange(row.time_slot) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="排班类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getScheduleTypeTag(row.schedule_type)" size="small">
              {{ formatScheduleType(row.schedule_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="业务信息"
          width="180"
          v-if="showBusinessColumns"
        >
          <template #default="{ row }">
            <div
              v-if="requiresBusinessInfo(row.schedule_type)"
              class="business-info"
            >
              <template v-if="row.schedule_type === 'outpatient'">
                <div>费用: ¥{{ formatAmount(row.fee_amount) }}</div>
                <div>号源: {{ row.max_patients }}个</div>
              </template>
              <template v-else-if="row.schedule_type === 'pharmacy'">
                <div>药房: {{ row.department_name || "主药房" }}</div>
                <div>服务类型: {{ row.service_type || "药品发放" }}</div>
              </template>
              <template
                v-else-if="
                  ['billing', 'registration'].includes(row.schedule_type)
                "
              >
                <div>窗口: {{ row.window_number || "1号窗口" }}</div>
                <div>服务范围: {{ row.service_scope || "全科" }}</div>
              </template>
              <template v-else>
                <span class="no-info">-</span>
              </template>
            </div>
            <span v-else class="no-info">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="工作地点" width="150" />
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.is_active"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons-cell">
              <el-button size="small" @click="editSchedule(row)"
                >编辑</el-button
              >
              <el-button
                size="small"
                type="primary"
                @click="viewScheduleDetails(row)"
              >
                详情
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="deleteSchedule(row)"
                :disabled="row.is_active === 1"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current_page"
          v-model:page-size="pagination.page_size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          :page-count="pagination.pageTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑排班对话框 -->
    <el-dialog
      v-model="scheduleDialog.visible"
      :title="scheduleDialog.is_edit ? '编辑排班模板' : '新增排班模板'"
      width="750px"
      :destroy-on-close="false"
    >
      <el-form
        :model="scheduleForm"
        label-width="100px"
        :rules="scheduleRules"
        ref="scheduleFormRef"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="人员类型" prop="staff_type">
              <el-select
                v-model="scheduleForm.staff_type"
                @change="handleStaffTypeChange"
                style="width: 100%"
              >
                <!-- 使用后端加载的人员类型选项 -->
                <el-option
                  v-for="type in staffTypeOptions"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选择人员" prop="staff_id">
              <el-select
                v-model="scheduleForm.staff_id"
                placeholder="请选择人员"
                style="width: 100%"
                filterable
                :filter-method="filterDialogStaffOptions"
              >
                <el-option
                  v-for="staff in filteredDialogStaffOptions"
                  :key="staff.value"
                  :label="staff.label"
                  :value="staff.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 新增科室选择行 -->
        <el-row :gutter="20" class="mt-10">
          <el-col :span="12">
            <el-form-item label="科室/部门" prop="department_id">
              <el-select
                v-model="scheduleForm.department_id"
                placeholder="请选择科室/部门"
                clearable
                filterable
                :filter-method="filterDepartmentOptions"
                @change="handleDialogDepartmentChange"
              >
                <el-option
                  v-for="dept in departmentOptions"
                  :key="dept.value"
                  :label="dept.label"
                  :value="dept.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="星期安排" prop="week_days">
              <el-select
                v-model="scheduleForm.week_days"
                multiple
                placeholder="选择星期"
                style="width: 100%"
              >
                <el-option label="周一" value="1" />
                <el-option label="周二" value="2" />
                <el-option label="周三" value="3" />
                <el-option label="周四" value="4" />
                <el-option label="周五" value="5" />
                <el-option label="周六" value="6" />
                <el-option label="周日" value="7" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班次时间" prop="time_slot">
              <el-select
                v-model="scheduleForm.time_slot_code"
                placeholder="选择班次"
                style="width: 100%"
              >
                <!-- 使用后端加载的班次选项 -->
                <el-option
                  v-for="slot in TimeSlotOptions"
                  :key="slot.value"
                  :label="slot.label"
                  :value="slot.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排班类型" prop="schedule_type">
              <el-select
                v-model="scheduleForm.schedule_type"
                @change="handleScheduleTypeChange"
                style="width: 100%"
              >
                <el-option
                  v-for="type in ScheduleTypeOptions"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作地点" prop="location">
              <el-input
                v-model="scheduleForm.location"
                placeholder="请输入工作地点"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 动态业务信息字段 -->
        <div v-if="requiresBusinessInfo(scheduleForm.schedule_type)">
          <el-divider>业务信息</el-divider>
          <el-row :gutter="20">
            <template v-if="scheduleForm.schedule_type === 'outpatient'">
              <el-col :span="12">
                <el-form-item label="费用项目" prop="fee_item_id">
                  <!-- 改为可输入快速搜索，并使用 filteredFeeItems -->
                  <el-select
                    v-model="scheduleForm.fee_item_id"
                    placeholder="选择费用项目"
                    style="width: 100%"
                    clearable
                    filterable
                    :filter-method="filterFeeItems"
                  >
                    <el-option
                      v-for="item in filteredFeeItems"
                      :key="item.value"
                      :label="`${item.label} (¥${item.amount})`"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="最大挂号数" prop="max_patients">
                  <el-input-number
                    v-model="scheduleForm.max_patients"
                    :min="1"
                    :max="100"
                    controls-position="right"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </template>

            <template v-else-if="scheduleForm.schedule_type === 'pharmacy'">
              <el-col :span="12">
                <el-form-item label="药房位置" prop="pharmacy_location">
                  <el-select
                    v-model="scheduleForm.pharmacy_location"
                    placeholder="选择药房"
                    style="width: 100%"
                  >
                    <el-option label="主药房" value="main" />
                    <el-option label="急诊药房" value="emergency" />
                    <el-option label="住院药房" value="inpatient" />
                    <el-option label="中药房" value="chinese" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="服务类型" prop="service_type">
                  <el-select
                    v-model="scheduleForm.service_type"
                    placeholder="选择服务类型"
                    style="width: 100%"
                  >
                    <el-option label="药品发放" value="dispensing" />
                    <el-option label="药品管理" value="management" />
                    <el-option label="处方审核" value="review" />
                    <el-option label="用药指导" value="guidance" />
                  </el-select>
                </el-form-item>
              </el-col>
            </template>

            <template
              v-else-if="
                ['billing', 'registration'].includes(scheduleForm.schedule_type)
              "
            >
              <el-col :span="12">
                <el-form-item label="窗口编号" prop="window_number">
                  <el-input
                    v-model="scheduleForm.window_number"
                    placeholder="如：1号窗口"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="服务范围" prop="service_scope">
                  <el-select
                    v-model="scheduleForm.service_scope"
                    placeholder="选择服务范围"
                    style="width: 100%"
                  >
                    <el-option label="全科" value="all" />
                    <el-option label="专科" value="special" />
                    <el-option label="急诊" value="emergency" />
                    <el-option label="住院" value="inpatient" />
                  </el-select>
                </el-form-item>
              </el-col>
            </template>
          </el-row>
        </div>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="is_active">
              <el-radio-group v-model="scheduleForm.is_active">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="scheduleForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button
          @click="scheduleDialog.visible = false"
          :disabled="submitting"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="submitScheduleForm"
          :loading="submitting"
          >确认</el-button
        >
      </template>
    </el-dialog>

    <!-- 批量操作对话框 -->
    <el-dialog
      v-model="batchDialog.visible"
      title="批量操作"
      width="500px"
      :destroy-on-close="false"
    >
      <el-form :model="batchForm" label-width="100px">
        <el-form-item label="操作类型">
          <el-radio-group v-model="batchForm.operation">
            <el-radio label="enable">启用选中</el-radio>
            <el-radio label="disable">停用选中</el-radio>
            <el-radio label="delete">删除选中</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="影响范围">
          <div>共选中 {{ batchForm.selectedCount }} 个排班</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmBatchOperation"
          >确认执行</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onUnmounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "vuex";
// 引入后端接口
import {
  getDoctorList,
  getNurseList,
  getPharmacistList,
  getFinanceStaffList,
  getDepartmentList,
  getStaffTypeList,
  getTimeSlotList,
  getScheduleTypeList,
  getFeeItemList,
  addScheduleTemplate,
  editScheduleTemplate,
  getScheduleTemplatePagerDataBySearch,
} from "@/api/api";

const store = useStore();

const loading = ref(false);

//===========数据类型预加载============
// 人员类型列表
const staffTypeList = ref([]); //所有人员列表
const scheduleTypeList = ref([]); //预加载排班类型类别数据
const timeSlotList = ref([]); // 班次时间选项

// 筛选条件
const filters = reactive({
  department_id: "",
  staff_type: "",
  staff_id: "",
  schedule_type: "",
  is_active: "",
});

// 统计信息
const stats = reactive({
  totalCount: 0,
  activeCount: 0,
  doctorCount: 0,
  nurseCount: 0,
  pharmacistCount: 0,
  staffCount: 0,
});

// 分页信息
const pagination = reactive({
  current_page: 1,
  page_size: 10,
  total: 0,
  pageTotal: 0,
});

// 数据选项
const departmentOptions = ref([]); // 科室/部门定义表，改为 {value,label}
const staffTypeOptions = ref([]); // 人员类型定义表，改为 {value,label}
const TimeSlotOptions = ref([]); // 班次时间定义表，改为 {value,label}
const ScheduleTypeOptions = ref([]); // 排班类型定义表，改为 {value,label}
const feeItemOptions = ref([]); // 费用项目列表，改为 {value,label,amount}
const filteredFeeItems = ref([]); // 展示前10条匹配项

//data
// 筛选后的选项
const filteredDepartmentOptions = ref([]);
const filteredStaffOptions = ref([]);
const filteredDialogStaffOptions = ref([]);

// 计算属性
const currentStaffOptions = computed(() => {
  return staffOptions.value[scheduleForm.staff_type] || [];
});

const showBusinessColumns = computed(() => {
  return schedules.value.some((schedule) =>
    requiresBusinessInfo(schedule.schedule_type)
  );
});

// 排班数据
const schedules = ref([]);

// 对话框控制
const scheduleDialog = reactive({
  visible: false,
  is_edit: false,
});

// 批量操作对话框
const batchDialog = reactive({
  visible: false,
});

const batchForm = reactive({
  operation: "enable",
  selectedCount: 0,
});

// 排班表单
const scheduleForm = reactive({
  schedule_id: null, // 新增：用于编辑时携带主键
  staff_type: "doctor",
  staff_id: "",
  week_days: [],
  time_slot_code: "morning",
  schedule_type: "outpatient",
  location: "", //工作地点
  // 业务相关字段
  fee_item_id: "",
  max_patients: 30,
  service_type: "",
  window_number: "",
  service_scope: "",
  pharmacy_location: "", //药房位置
  is_active: 1,
  notes: "",
  department_id: "", // 新增科室字段
  created_by: store.state.user?.user_id, // 新增创建人ID
  updated_by: store.state.user?.user_id, // 新增更新人ID
});

// 表单验证规则
const scheduleRules = {
  staff_id: [{ required: true, message: "请选择人员", trigger: "change" }],
  week_days: [{ required: true, message: "请选择星期", trigger: "change" }],
  time_slot_code: [
    { required: true, message: "请选择班次", trigger: "change" },
  ],
  schedule_type: [
    { required: true, message: "请选择排班类型", trigger: "change" },
  ],
  location: [{ required: true, message: "请输入工作地点", trigger: "blur" }],
};

const scheduleFormRef = ref(null);

// 详情抽屉
const detailDrawer = reactive({
  visible: false,
});

const currentSchedule = ref(null);

// 新增：选中行与提交状态
const selectedRows = ref([]);
const submitting = ref(false);

// 方法定义
const resetFilters = () => {
  Object.keys(filters).forEach((key) => {
    filters[key] = "";
  });
  loadSchedules();
};

const searchSchedules = () => {
  pagination.current_page = 1;
  loadSchedules();
};

const handleDepartmentChange = (deptId) => {
  loadStaffOptions(deptId);
};

// 星期颜色样式筛选方法
const getWeekDayClass = (day) => {
  const classMap = {
    '1': 'monday',
    '2': 'tuesday', 
    '3': 'wednesday',
    '4': 'thursday',
    '5': 'friday',
    '6': 'saturday',
    '7': 'sunday'
  };
  return classMap[day] || '';
};

// 科室筛选方法
const filterDepartmentOptions = (query) => {
  if (query) {
    const filtered = allDepartmentOptions.value.filter((dept) =>
      dept.label.toLowerCase().includes(query.toLowerCase())
    );
    filteredDepartmentOptions.value = filtered.slice(0, 10); // 限制显示10条
  } else {
    filteredDepartmentOptions.value = allDepartmentOptions.value.slice(0, 10);
  }
};

// 人员筛选方法（主筛选区域）
const filterStaffOptions = (query) => {
  let staffList = [];

  if (filters.staff_type && staffOptions.value[filters.staff_type]) {
    staffList = staffOptions.value[filters.staff_type];
  } else {
    staffList = Object.values(staffOptions.value).flat();
  }

  if (query) {
    const filtered = staffList.filter((staff) =>
      staff.label.toLowerCase().includes(query.toLowerCase())
    );
    filteredStaffOptions.value = filtered.slice(0, 10);
  } else {
    filteredStaffOptions.value = staffList.slice(0, 10);
  }
};

// 对话框内人员筛选方法（增强：按科室 + 人员类型过滤）
const filterDialogStaffOptions = (query) => {
  const staffList = staffOptions.value[scheduleForm.staff_type] || [];

  let list = staffList;
  if (scheduleForm.department_id) {
    list = list.filter(
      (s) => String(s.department_id) === String(scheduleForm.department_id)
    );
  }

  if (query) {
    const filtered = list.filter((staff) =>
      staff.label.toLowerCase().includes(query.toLowerCase())
    );
    filteredDialogStaffOptions.value = filtered.slice(0, 50);
  } else {
    filteredDialogStaffOptions.value = list.slice(0, 50);
  }
};

// 费用项目本地过滤（输入搜索），优先匹配所属科室，如果 scheduleForm.department_id 存在则优先显示包含该科室的项目
const filterFeeItems = (query) => {
  const q = (query || "").trim().toLowerCase();
  const deptId = scheduleForm.department_id
    ? String(scheduleForm.department_id)
    : null;

  if (!q && !deptId) {
    filteredFeeItems.value = feeItemOptions.value.slice(0, 10);
    return;
  }

  // 匹配函数：名称、编码包含 query
  const matchScore = (item) => {
    const name = (item.label || "").toLowerCase();
    const code = (
      (item.raw && (item.raw.item_code || item.raw.fee_item_code)) ||
      ""
    ).toLowerCase();
    let score = 0;
    if (name === q) score += 100;
    if (name.includes(q)) score += 50;
    if (code === q) score += 40;
    if (code.includes(q)) score += 20;
    return score;
  };

  const list = feeItemOptions.value
    .map((item) => {
      const score = q ? matchScore(item) : 0;
      // 如果存在科室过滤，给包含该科室的项目加权
      const deptMatch =
        deptId && item.department_ids
          ? item.department_ids
              .split(",")
              .map((s) => s.trim())
              .includes(deptId)
          : false;
      return {
        item,
        score: score + (deptMatch ? 30 : 0),
        deptMatch,
      };
    })
    .filter(({ item, score }) => {
      // 当有 query 时至少 name/code 包含 query 或 deptMatch；无 query 时只根据 deptMatch 或都保留
      if (q) {
        const name = (item.label || "").toLowerCase();
        const code = (
          (item.raw && (item.raw.item_code || item.raw.fee_item_code)) ||
          ""
        ).toLowerCase();
        return (
          name.includes(q) ||
          code.includes(q) ||
          (deptId &&
            item.department_ids &&
            item.department_ids
              .split(",")
              .map((s) => s.trim())
              .includes(deptId))
        );
      }
      if (deptId) {
        return (
          item.department_ids &&
          item.department_ids
            .split(",")
            .map((s) => s.trim())
            .includes(deptId)
        );
      }
      return true;
    })
    .sort((a, b) => b.score - a.score)
    .map((it) => it.item);

  filteredFeeItems.value = list.slice(0, 10);
};

// 对话框科室变化时，按科室加载人员并重置已选人员
const handleDialogDepartmentChange = (deptId) => {
  scheduleForm.staff_id = "";
  // loadStaffOptions 会根据传入 deptId 只保留该科室人员
  loadStaffOptions(deptId);
  // 重新过滤对话框人员
  filterDialogStaffOptions("");
  // 重新过滤费用项目（显示与科室相关的优先项）
  filterFeeItems("");
};

const allDepartmentOptions = ref([]); // 保存完整的科室列表

// 数据加载
//加载科室/部门列表
const load_departments_list = async () => {
  try {
    const response = await getDepartmentList();
    if (response && response.data) {
      departmentOptions.value = response.data.map((dept) => ({
        value: dept.department_id,
        label: dept.department_name,
      }));
      allDepartmentOptions.value = [...departmentOptions.value]; // 保存完整列表
      filteredDepartmentOptions.value = allDepartmentOptions.value.slice(0, 10); // 初始显示前10条
    }
  } catch (error) {
    console.error("加载科室列表失败:", error);
  }
};

// 加载人员类型定义表（增强兼容不同后端字段）
const load_staff_types = async () => {
  try {
    const response = await getStaffTypeList();
    // console.log("人员类型响应:", response);
    if (response && response.data) {
      // 支持后端返回多种字段结构：{type,name} 或 {id,name} 或 {value,label}
      staffTypeOptions.value = response.data.map((item) => {
        return {
          value: item.type_code || "",
          label: item.type_name || "",
        };
      });
      staffTypeList.value = response.data; //保存原始数据
    }
  } catch (error) {
    console.error("加载人员类型定义失败:", error);
  }
};

// 加载时间班次定义表（增强兼容）
const load_time_slots = async () => {
  try {
    const response = await getTimeSlotList();
    // console.log("时间班次响应:", response);
    if (response && response.data) {
      TimeSlotOptions.value = response.data.map((item) => {
        return {
          value: item.slot_code || "",
          label: item.slot_name || "",
        };
      });
      timeSlotList.value = response.data; //保存原始数据
    }
  } catch (error) {
    console.error("加载时间班次定义失败:", error);
  }
};

// 加载排班类型定义表（增强兼容）
const load_schedule_types = async () => {
  try {
    const response = await getScheduleTypeList();
    // console.log("排班类型响应:", response);
    if (response && response.data) {
      ScheduleTypeOptions.value = response.data.map((item) => {
        return {
          value: item.type_code || "",
          label: item.type_name || "",
        };
      });
      scheduleTypeList.value = response.data; //保存原始数据
    }
  } catch (error) {
    console.error("加载排班类型定义失败:", error);
  }
};

//预加载各个角色数据，避免重复请求
const doctorListData = ref([]);
const nurseListData = ref([]);
const pharmacistListData = ref([]);
const financeListData = ref([]);

// 加载医生列表（初始加载全部人员）
const load_doctor_list = async () => {
  try {
    const res = await getDoctorList();
    if (res && res.code == 200) {
      //加载并装载数据
      // doctorListData = res.data;
      // 转换为 {value,label} 结构
      staffOptions.value.doctor = res.data.map((doc) => ({
        value: doc.doctor_id,
        label: `${doc.doctor_name} - ${doc.department_name}`,
        department_id: doc.department_id,
        professional_title: doc.professional_title,
      }));
      // 初始化筛选后的人员列表
      filterStaffOptions("");
      filterDialogStaffOptions("");
    }
  } catch (error) {
    console.error("加载医生列表失败:", error);
  }
};

// 加载护士列表（初始加载全部人员）
const load_nurse_list = async () => {
  try {
    const res = await getNurseList();
    if (res && res.code == 200) {
      //加载并装载数据
      // nurseListData = res.data;
      // 转换为 {value,label} 结构
      staffOptions.value.nurse = res.data.map((nurse) => ({
        value: nurse.nurse_id,
        label: `${nurse.nurse_name} - ${nurse.department_name}`,
        department_id: nurse.department_id,
        professional_title: nurse.professional_title,
      }));
      // 初始化筛选后的人员列表
      filterStaffOptions("");
      filterDialogStaffOptions("");
    }
  } catch (error) {
    console.error("加载护士列表失败:", error);
  }
};

// 加载药剂师列表（初始加载全部人员）
const load_pharmacist_list = async () => {
  try {
    const res = await getPharmacistList();
    // console.log("药剂师列表响应:", response);
    if (res && res.code == 200) {
      //加载并装载数据
      // pharmacistListData = response.data;
      // 转换为 {value,label} 结构
      staffOptions.value.pharmacist = res.data.map((pharm) => ({
        value: pharm.pharmacist_id,
        label: `${pharm.pharmacist_name} - ${pharm.department_name}`,
        department_id: pharm.department_id,
        professional_title: pharm.professional_title,
      }));
      // 初始化筛选后的人员列表
      filterStaffOptions("");
      filterDialogStaffOptions("");
    }
  } catch (error) {
    console.error("加载药剂师列表失败:", error);
  }
};

// 加载财务人员列表（初始加载全部人员）
const load_finance_list = async () => {
  try {
    const response = await getFinanceStaffList();
    // console.log("财务人员列表响应:", response);
    if (response && response.data) {
      //加载并装载数据
      financeListData = response.data;
      // 转换为 {value,label} 结构
      staffOptions.value.finance = response.data.map((fin) => ({
        value: fin.finance_id,
        label: `${fin.finance_name} - ${fin.department_name}`,
        department_id: fin.department_id,
        professional_title: fin.professional_title || "财务人员",
      }));
      // 初始化筛选后的人员列表
      filterStaffOptions("");
      filterDialogStaffOptions("");
    }
  } catch (error) {
    console.error("加载财务人员列表失败:", error);
  }
};

const staffOptions = ref({
  doctor: [],
  nurse: [],
  pharmacist: [],
  finance: [],
  administrative: [],
  logistics: [],
});

// 数据加载
const loadStaffOptions = async (deptId = null) => {
  try {
    // 先从后端加载医生列表，确保医生数据来自真实接口
    let doctorList = [];
    try {
      const resp = await getDoctorList();
      if (resp && resp.data) {
        doctorList = resp.data.map((doc) => ({
          value: doc.doctor_id,
          label: `${doc.doctor_name} - ${doc.department_name}`,
          department_id: String(doc.department_id),
          professional_title: doc.professional_title,
        }));
      }
    } catch (e) {
      console.error("加载医生列表失败（loadStaffOptions）:", e);
      doctorList = []; // 回退为空数组，避免抛出
    }

    //加载护士列表
    let nurseList = [];
    try {
      const resp = await getNurseList();
      if (resp && resp.data) {
        nurseList = resp.data.map((nurse) => ({
          value: nurse.nurse_id,
          label: `${nurse.nurse_name} - ${nurse.department_name}`,
          department_id: String(nurse.department_id),
          professional_title: nurse.professional_title,
        }));
      }
    } catch (e) {
      console.error("加载护士列表失败（loadStaffOptions）:", e);
      nurseList = []; // 回退为空数组，避免抛出
    }

    //加载药剂师列表
    let pharmacistList = [];
    try {
      const resp = await getPharmacistList();
      if (resp && resp.data) {
        pharmacistList = resp.data.map((pharm) => ({
          value: pharm.pharmacist_id,
          label: `${pharm.pharmacist_name} - ${pharm.department_name}`,
          department_id: String(pharm.department_id),
          professional_title: pharm.professional_title,
        }));
      }
    } catch (e) {
      console.error("加载药剂师列表失败（loadStaffOptions）:", e);
      pharmacistList = []; // 回退为空数组，避免抛出
    }

    let financeList = [];
    try {
      const resp = await getFinanceStaffList();
      if (resp && resp.data) {
        financeList = resp.data.map((fin) => ({
          value: fin.finance_id,
          label: `${fin.finance_name} - ${fin.department_name}`,
          department_id: String(fin.department_id),
          professional_title: fin.professional_title || "财务人员",
        }));
      }
    } catch (e) {
      console.error("加载财务人员列表失败（loadStaffOptions）:", e);
      financeList = []; // 回退为空数组，避免抛出
    }

    // 其它人员类型保留模板，后续你可以替换为真实接口
    const templateOptions = {
      doctor: doctorList,
      nurse: nurseList,
      pharmacist: pharmacistList,
      finance: financeList,
      administrative: [],
      logistics: [],
    };

    // 如果指定了科室，按科室过滤每种类型的人员（注意全部转换为字符串比较）
    if (deptId) {
      Object.keys(templateOptions).forEach((type) => {
        templateOptions[type] = (templateOptions[type] || []).filter(
          (staff) => String(staff.department_id) === String(deptId)
        );
      });
    }

    // 最终赋值并刷新筛选列表
    staffOptions.value = templateOptions;
    filterStaffOptions("");
    filterDialogStaffOptions("");
  } catch (error) {
    console.error("加载人员列表失败:", error);
  }
};

// 判断是否需要业务信息
const requiresBusinessInfo = (scheduleType) => {
  return ["outpatient", "pharmacy", "billing", "registration"].includes(
    scheduleType
  );
};

// 获取人员类型图标
const getStaffTypeIcon = (type) => {
  const iconMap = {
    doctor: "👨‍⚕️",
    nurse: "👩‍⚕️",
    pharmacist: "💊",
    finance: "💰",
    registration: "🏥",
    administrative: "📋",
    logistics: "🔧",
  };
  return iconMap[type] || "👤";
};

// 格式化人员类型
const formatStaffType = (type) => {
  staffTypeList.value = staffTypeList.value || [];
  const typeObj = staffTypeList.value.find((t) => t.type_code === type);
  return typeObj ? typeObj.type_name : type || "";
};

// 格式化星期
const formatTimeRange = (slot) => {
  const rangeMap = {
    morning: "07:00-15:00",
    afternoon: "15:00-23:00",
    night: "23:00-07:00",
    full_day: "08:00-17:00",
    office: "09:00-18:00",
    flexible: "弹性时间",
    off: "休息",
  };
  return rangeMap[slot] || "";
};

const getWeekDayType = (day) => {
  const types = [
    "",
    "success",
    "warning",
    "danger",
    "info",
    "success",
    "warning",
    "danger",
  ];
  return types[parseInt(day)] || "";
};

const getScheduleTypeTag = (type) => {
  const tagMap = {
    outpatient: "success",
    inpatient: "primary",
    pharmacy: "warning",
    billing: "danger",
    registration: "info",
    office: "",
    service: "warning",
    emergency: "danger",
    surgery: "success",
  };
  return tagMap[type] || "info";
};

// 显示批量操作对话框
const showBatchOperationDialog = () => {
  const selectedCount = selectedRows.value.length;
  if (selectedCount === 0) {
    ElMessage.warning("请先选择要操作的排班");
    return;
  }
  batchForm.selectedCount = selectedCount;
  batchDialog.visible = true;
};

// 确认批量操作
const confirmBatchOperation = () => {
  ElMessage.success(`批量${batchForm.operation}操作成功`);
  batchDialog.visible = false;
  loadSchedules();
};
// 加载费用项目列表数据（兼容后端结构，并初始化 filteredFeeItems）
const loadFeeItemOptions = async () => {
  try {
    const response = await getFeeItemList();
    // 后端返回示例以 { code: 200, msg: "", data: [ { item_id, item_name, standard_price, department_ids, ... } ] }
    if (
      response &&
      (response.code === 200 || response.code === "200") &&
      Array.isArray(response.data)
    ) {
      feeItemOptions.value = response.data.map((it) => ({
        value: it.item_id != null ? String(it.item_id) : "",
        label: it.item_name || it.item_code || "",
        amount:
          it.standard_price != null ? it.standard_price : it.fee_amount || 0,
        department_ids:
          it.department_ids != null ? String(it.department_ids) : "",
        raw: it,
      }));
      // 初始展示前10条
      filteredFeeItems.value = feeItemOptions.value.slice(0, 10);
    } else if (response && response.data) {
      // 兼容旧结构
      feeItemOptions.value = (response.data || []).map((item) => ({
        value: item.fee_item_id || item.item_id || "",
        label: item.fee_item_name || item.item_name || "",
        amount: item.fee_amount || item.standard_price || 0,
        department_ids: item.department_ids ? String(item.department_ids) : "",
        raw: item,
      }));
      filteredFeeItems.value = feeItemOptions.value.slice(0, 10);
    } else {
      feeItemOptions.value = [];
      filteredFeeItems.value = [];
    }
  } catch (error) {
    console.error("加载费用项目失败:", error);
    feeItemOptions.value = [];
    filteredFeeItems.value = [];
  }
};

// 替换为动态构建参数并调用接口
const loadSchedules = async () => {
  try {
    // 按后端接收字段严格构建参数并进行类型转换
    const params = {
      staff_id:
        filters.staff_id !== "" && filters.staff_id != null
          ? Number(filters.staff_id)
          : undefined,
      staff_type_code: filters.staff_type || undefined,
      schedule_type: filters.schedule_type || undefined,
      department_id:
        filters.department_id !== "" && filters.department_id != null
          ? Number(filters.department_id)
          : undefined,
      is_active:
        filters.is_active !== "" && filters.is_active != null
          ? Number(filters.is_active)
          : undefined,
      currentPage: pagination.current_page,
      pageSize: pagination.page_size,
    };

    // console.log("请求参数:", params);

    const response = await getScheduleTemplatePagerDataBySearch(params);

    // console.log("排班数据响应:", response);

    if (!response || response.code !== 200) {
      ElMessage.error("加载排班数据失败");
      return;
    }

    const dataList = Array.isArray(response.data?.data)
      ? response.data.data
      : [];

    // 规范化每条记录：
    // - week_days 保证为数组，例如 "1,3,5" -> ["1","3","5"]
    // - time_slot 优先使用 time_slot 字段，否则使用 time_slot_code（后端不同命名兼容）
    const normalized = dataList.map((it) => {
      const item = { ...it };

      // 统一人员名称字段
      if (!item.staff_name) {
        // 如果没有staff_name，根据人员类型使用不同的字段
        if (item.staff_type === "doctor" && item.doctor_staff_name) {
          item.staff_name = item.doctor_staff_name;
        } else if (item.staff_type === "nurse" && item.nurse_staff_name) {
          item.staff_name = item.nurse_staff_name;
        } else if (
          item.staff_type === "pharmacist" &&
          item.pharmacist_staff_name
        ) {
          item.staff_name = item.pharmacist_staff_name;
        } else if (item.staff_type === "finance" && item.finance_staff_name) {
          item.staff_name = item.finance_staff_name;
        } else {
          item.staff_name = "未知人员";
        }
      }

      // 统一职称字段
      if (!item.professional_title) {
        if (item.staff_type === "doctor" && item.doctor_professional_title) {
          item.professional_title = item.doctor_professional_title;
        } else if (
          item.staff_type === "nurse" &&
          item.nurse_professional_title
        ) {
          item.professional_title = item.nurse_professional_title;
        }
      }

      // 规范 week_days（与之前相同）
      if (Array.isArray(item.week_days)) {
        item.week_days = item.week_days.map((d) => String(d));
      } else if (typeof item.week_days === "string") {
        item.week_days = item.week_days
          .split(",")
          .map((s) => s.trim())
          .filter((s) => s !== "");
      } else if (typeof item.week_days === "number") {
        item.week_days = [String(item.week_days)];
      } else {
        item.week_days = [];
      }

      // 统一班次字段
      item.time_slot = item.time_slot || item.time_slot_code || "";

      // 费用金额
      if (item.fee_amount === null || item.fee_amount === undefined) {
        item.fee_amount = item.standard_price || 0;
      }

      return item;
    });

    schedules.value = normalized;
    pagination.total = response.data?.total || normalized.length;
    pagination.pageTotal = response.data?.pageTotal || 0;
    updateStats(response.data.dataStatus);
  } catch (error) {
    console.error("加载排班数据失败:", error);
    ElMessage.error("加载排班数据失败");
  }
};

const updateStats = (data) => {
  stats.totalCount = data.total_schedules;
  stats.activeCount = data.active_schedules;
  stats.doctorCount = data.doctor_schedules;
  stats.nurseCount = data.nurse_schedules;
  stats.pharmacistCount = data.pharmacist_schedules;
  stats.staffCount = data.other_staff_schedules;
};

const handleSizeChange = (size) => {
  pagination.page_size = size;
  loadSchedules();
};

const handleCurrentChange = (page) => {
  pagination.current_page = page;
  loadSchedules();
};

const handleStatusChange = async (row) => {
  try {
    // TODO: 调用后端接口更新状态
    const params = {
      schedule_id: row.schedule_id || row.id,
      is_active: row.is_active,
    };
    const res = await editScheduleTemplate(params);
    if (res && res.code == 200) {
      ElMessage.success(`已${row.is_active ? "启用" : "停用"}排班`);
    }

    loadSchedules();
  } catch (error) {
    console.error("更新状态失败:", error);
    ElMessage.error("更新状态失败");
    // 恢复原状态
    row.is_active = row.is_active ? 0 : 1;
  }
};

const showAddScheduleDialog = () => {
  scheduleDialog.is_edit = false;
  scheduleDialog.visible = true;
  resetScheduleForm();
};

// 编辑时确保带上主键 schedule_id（兼容后端返回 id 或 schedule_id）
const editSchedule = (row) => {
  scheduleDialog.is_edit = true;
  scheduleDialog.visible = true;
  // 把后端数据合并到表单
  Object.assign(scheduleForm, row);
  // 添加这行 - 确保 staff_type_code 有值
  scheduleForm.staff_type_code = row.staff_type_code || row.staff_type;
  // 优先使用 schedule_id，其次兼容 id 字段
  scheduleForm.schedule_id = row.schedule_id || row.id || null;
  // 确保 department_id 存在
  scheduleForm.department_id =
    row.department_id || scheduleForm.department_id || "";

  // 修复：确保 fee_item_id 为字符串，且将当前已选费用项放到 filteredFeeItems 中以便 Select 能显示
  if (row.fee_item_id !== undefined && row.fee_item_id !== null) {
    const fid = String(row.fee_item_id);
    scheduleForm.fee_item_id = fid;

    // 如果 feeItemOptions 中存在该项，把它放到 filteredFeeItems 的前面；否则创建占位项
    const found = feeItemOptions.value.find((it) => String(it.value) === fid);
    if (found) {
      filteredFeeItems.value = [
        found,
        ...filteredFeeItems.value.filter((it) => String(it.value) !== fid),
      ].slice(0, 10);
    } else {
      // 后端可能未返回完整的费用项信息，添加一个占位项以显示当前选择
      const placeholder = {
        value: fid,
        label: row.fee_item_name || "已选费用项",
        amount: row.fee_amount != null ? row.fee_amount : 0,
        raw: row,
      };
      filteredFeeItems.value = [placeholder, ...filteredFeeItems.value].slice(
        0,
        10
      );
    }
  }

  // 按科室加载人员选项，保证对话框人员列表正确
  if (scheduleForm.department_id) {
    loadStaffOptions(scheduleForm.department_id);
    filterDialogStaffOptions("");
  }
};

const viewScheduleDetails = (row) => {
  currentSchedule.value = row;
  detailDrawer.visible = true;
};

const deleteSchedule = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除 ${row.staff_name} 的排班吗？`,
      "确认删除",
      {
        type: "warning",
      }
    );
    // TODO: 调用后端接口删除排班
    ElMessage.success("删除成功");
    loadSchedules();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

const resetScheduleForm = () => {
  // 保存需要保留的初始值
  const currentUserId = store.state.user?.user_id;

  // 完全重置表单对象
  Object.assign(scheduleForm, {
    schedule_id: null,
    staff_type: "doctor",
    staff_id: "",
    week_days: [],
    time_slot_code: "morning",
    schedule_type: "outpatient",
    location: "",
    fee_item_id: "",
    max_patients: 30,
    service_type: "",
    window_number: "",
    service_scope: "",
    pharmacy_location: "",
    is_active: 1,
    notes: "",
    department_id: "",
    created_by: currentUserId,
    updated_by: currentUserId,
  });
};

const handleStaffTypeChange = () => {
  scheduleForm.staff_id = "";
  filterDialogStaffOptions("");
};

const handleScheduleTypeChange = () => {
  // 重置业务相关字段
  scheduleForm.fee_item_id = "";
  scheduleForm.pharmacy_location = "";
  scheduleForm.service_type = "";
  scheduleForm.window_number = "";
  scheduleForm.service_scope = "";
};

// 提交表单：构建严格匹配数据库字段的 payload
const submitScheduleForm = async () => {
  try {
    await scheduleFormRef.value.validate();
  } catch (err) {
    // 表单校验未通过，直接返回
    return;
  }

  submitting.value = true;
  try {
    const payload = { ...scheduleForm };
    payload.week_days = Array.isArray(payload.week_days)
      ? payload.week_days.join(",")
      : "";

    // 添加这行 - 将 staff_type 映射为 staff_type_code
    payload.staff_type_code = payload.staff_type;

    // 确保 schedule_id 存在于编辑时
    if (scheduleDialog.is_edit) {
      if (!payload.schedule_id) {
        ElMessage.error("编辑排班时缺少排班ID");
        submitting.value = false;
        return;
      }
    } else {
      // 新增时移除 schedule_id，避免干扰后端
      delete payload.schedule_id;
    }

    // 必须在提交时使用当前登录账户 id 作为更新者/创建者，避免使用初始化时的旧值
    const currentUserId = store.state.user?.user_id;
    if (scheduleDialog.is_edit) {
      payload.updated_by = currentUserId;
    } else {
      payload.created_by = currentUserId;
      // 新增时也可标注创建者作为 updated_by（根据后端需要可选）
      payload.updated_by = currentUserId;
    }

    // 如果 fee_item_id 是字符串且后端期望数字，可在这里转换（视后端要求）
    // if (payload.fee_item_id) payload.fee_item_id = Number(payload.fee_item_id);

    console.log("提交的排班 payload:", payload);

    let response;
    //根据 is_edit 调用不同接口
    if (scheduleDialog.is_edit) {
      response = await editScheduleTemplate(payload);
    } else {
      response = await addScheduleTemplate(payload);
    }

    if (response && response.code === 200) {
      ElMessage.success(scheduleDialog.is_edit ? "更新成功" : "新增成功");
      scheduleDialog.visible = false;
      resetScheduleForm();

      // 重新加载人员选项数据，确保下拉框数据最新
      await loadStaffOptions();
      // 重新过滤对话框人员选项
      filterDialogStaffOptions("");
      // 重新过滤主筛选区域人员选项
      filterStaffOptions("");

      await loadSchedules();
    } else {
      ElMessage.error(response?.message || "操作失败");
    }
  } catch (error) {
    console.error("保存排班失败:", error);
    ElMessage.error("保存排班失败");
  } finally {
    submitting.value = false;
  }
};

const generateWeeklySchedule = () => {
  ElMessage.info("生成周排班功能开发中...");
};

const exportSchedule = () => {
  ElMessage.info("导出排班表功能开发中...");
};

const refreshData = () => {
  loadSchedules();
  ElMessage.success("数据已刷新");
};

// 格式化函数
const formatWeekDay = (day) => {
  const days = ["", "一", "二", "三", "四", "五", "六", "日"];
  return `周${days[parseInt(day)]}`;
};

const formatTimeSlot = (slot) => {
  timeSlotList.value = timeSlotList.value || [];
  const slotObj = timeSlotList.value.find(
    (s) => s.slot_code === slot || s.value === slot
  );
  return slotObj ? slotObj.slot_name : slot || "";
};

const formatScheduleType = (type) => {
  scheduleTypeList.value = scheduleTypeList.value || [];
  const typeObj = scheduleTypeList.value.find(
    (t) => t.type_code === type || t.value === type
  );
  return typeObj ? typeObj.type_name : type || "";
};

const formatAmount = (amount) => {
  return parseFloat(amount || 0).toFixed(2);
};

const getShiftType = (slot) => {
  const typeMap = {
    morning: "success",
    afternoon: "warning",
    night: "danger",
    full_day: "primary",
    office: "info",
    flexible: "",
    off: "info",
  };
  return typeMap[slot] || "info";
};

// 初始化数据
const initData = async () => {
  try {
    await load_doctor_list(); //预加载医生列表数据
    await load_nurse_list(); //预加载护士列表数据
    await load_pharmacist_list(); //预加载药剂师列表数据
    await load_departments_list(); //预加载科室列表数据
    await load_staff_types(); //预加载人员类型定义表
    await load_time_slots(); // 预加载时间班次定义表
    await load_schedule_types(); // 预加载排班类型定义表
    // 初始显示前10条科室
    filteredDepartmentOptions.value = allDepartmentOptions.value.slice(0, 10);

    await loadStaffOptions(); //预加载全部人员列表数据
    await loadFeeItemOptions(); //预加载费用项目列表数据
    await loadSchedules(); //加载排班数据
    ElMessage.success("数据初始化完成");
  } catch (error) {
    console.error("初始化数据失败:", error);
  }
};

onMounted(() => {
  // 延迟初始化，让 DOM 完全稳定
  setTimeout(() => {
    initData();
  }, 500);
});
</script>

<style lang="scss" scoped>
.content-area {
  flex: 1;
  padding: 24px;
  background-color: #f5f7fa;
  height: 0; // 添加这行
  min-height: 100%; // 添加这行
  overflow-y: auto; // 确保有这行
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  border-radius: 8px;
  margin-right: 15px;
  font-size: 24px;
}

.stat-icon.total {
  background: #e8f4ff;
  color: #1890ff;
}

.stat-icon.active {
  background: #f0f9ff;
  color: #52c41a;
}

.stat-icon.doctor {
  background: #fff7e6;
  color: #fa8c16;
}

.stat-icon.nurse {
  background: #fff0f6;
  color: #eb2f96;
}

.stat-icon.pharmacist {
  background: #f6ffed;
  color: #52c41a;
}

.stat-icon.staff {
  background: #f9f0ff;
  color: #722ed1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-top: 4px;
}

.filter-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  min-width: 200px;
  flex: 1;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.schedule-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.table-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.table-tools {
  display: flex;
  gap: 10px;
}

.staff-info {
  display: flex;
  align-items: center;
}

.staff-avatar {
  margin-right: 12px;
}

.avatar-text {
  font-size: 18px;
}

.staff-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.staff-details {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}

.week-days {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.week-day-tag {
  margin: 1px;  
}

.week-day-tag.monday {
  background-color: rgba(255, 107, 53, 0.2) !important;
  color: #f8551a !important;
}

.week-day-tag.tuesday {
  background-color: rgba(52, 152, 219, 0.2) !important;
  color: #3498DB !important;
}

.week-day-tag.wednesday {
  background-color: rgba(46, 204, 113, 0.2) !important;
  color: #2ECC71 !important;
}

.week-day-tag.thursday {
  background-color: rgba(155, 89, 182, 0.2) !important;
  color: #9B59B6 !important;
}

.week-day-tag.friday {
  background-color: rgba(231, 76, 60, 0.2) !important;
  color: #E74C3C !important;
}

.week-day-tag.saturday {
  background-color: rgba(241, 196, 15, 0.2) !important;
  color: #7D6608 !important;
}

.week-day-tag.sunday {
  background-color: rgba(255, 159, 243, 0.2) !important;
  color: #6C3483 !important;
}

.time-slot-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.time-range {
  font-size: 12px;
  color: #909399;
}

.business-info {
  font-size: 12px;
  line-height: 1.4;
}

.no-info {
  color: #c0c4cc;
  font-style: italic;
}

.action-buttons-cell {
  display: flex;
  gap: 8px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  padding: 20px;
  border-top: 1px solid #ebeef5;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-tag) {
  border: none;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-divider__text) {
  background-color: white;
  font-size: 14px;
  color: #606266;
}

@media (max-width: 1200px) {
  .filter-row {
    flex-direction: column;
  }

  .filter-item {
    min-width: 100%;
  }

  .action-buttons {
    flex-direction: column;
  }

  .table-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
}

@media (max-width: 768px) {
  .content-area {
    padding: 10px;
  }

  .stat-card {
    padding: 15px;
  }

  .stat-icon {
    width: 50px;
    height: 50px;
    font-size: 20px;
  }

  .stat-value {
    font-size: 20px;
  }

  .filter-card {
    padding: 15px;
  }

  .table-header {
    padding: 15px;
  }

  .action-buttons-cell {
    flex-direction: column;
  }
}
</style>